<template>
  <div>
    <div class="i-layout-page-header">
      <i-page-header title="权限栏目组"></i-page-header>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form ref="formValidate" :model="formValidate">
        <Row type="flex">
          <Col v-bind="grid">
            <el-button
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="classAdd"
              class="mr20"
              >添加权限数据</el-button
            >
          </Col>
        </Row>
      </Form>
      <vxe-table
        :border="false"
        class="vxeTable mt25"
        highlight-hover-row
        highlight-current-row
        :loading="loading"
        ref="xTable"
        header-row-class-name="false"
        :tree-config="{ children: 'children' }"
        @toggle-tree-expand="tapTreeExpand"
        :data="classList"
      >
        <vxe-table-column
          field="id"
          title="ID"
          tooltip
          min-width="40"
        ></vxe-table-column>
        <vxe-table-column
          field="title"
          tree-node
          title="权限标题"
          min-width="150"
        ></vxe-table-column>
        <vxe-table-column
          field="role_path"
          title="接口权限"
          min-width="400"
        ></vxe-table-column>
        <vxe-table-column
          field="menu_title"
          title="绑定菜单"
          min-width="100"
        ></vxe-table-column>
        <vxe-table-column
          field="seq"
          title="排序"
          min-width="50"
        ></vxe-table-column>

        <vxe-table-column field="is_show" title="状态" min-width="50">
          <template v-slot="{ row }">
            <i-switch
              v-model="row.is_show"
              :value="row.is_show"
              :true-value="1"
              :false-value="0"
              @on-change="onchangeIsShow(row)"
              size="large"
            >
              <span slot="open">显示</span>
              <span slot="close">隐藏</span>
            </i-switch>
          </template>
        </vxe-table-column>
        <vxe-table-column
          field="action"
          title="操作"
          min-width="100"
          fixed="right"
        >
          <template v-slot="{ row, index }">
            <a @click="edit(row)">编辑</a>
            <Divider type="vertical" />
            <a @click="del(row, '删除分类', index)">删除</a>
          </template>
        </vxe-table-column>
      </vxe-table>
    </Card>

    <Modal v-model="dialogVisible" :title="title" @on-cancel="editClose">
      <el-form ref="menu" :model="menu" label-width="80px">
        <el-form-item
          label="权限名称"
          prop="title"
          :rules="[{ required: true, message: '请输入权限名称' }]"
        >
          <el-input
            placeholder="请输入权限名称"
            autocomplete="off"
            v-model="menu.title"
          ></el-input>
        </el-form-item>

        <el-form-item label="顶部栏目">
          <el-select
            v-model="menu.pid"
            placeholder="顶部栏目"
            style="width: 100%"
          >
            <el-option
              :label="item.html + item.title"
              :value="item.id"
              :key="item.id"
              v-for="item in pathAr"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="权限数据">
          <el-input
            type="textarea"
            :autosize="{ minRows: 5 }"
            placeholder="权限数据用逗号隔开"
            v-model="menu.role_path"
          ></el-input>
        </el-form-item>

        <el-form-item label="绑定菜单">
          <el-select
            v-model="menu.menu_id"
            placeholder="绑定菜单"
            style="width: 100%"
          >
            <el-option
              :label="item.html + item.title"
              :value="item.id"
              :key="item.id"
              v-for="item in menuAr"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序">
          <el-input placeholder="排序越高越前面" v-model="menu.seq"></el-input>
        </el-form-item>

        <el-form-item label="是否禁用" style="margin-bottom: 0">
          <el-radio-group v-model="menu.is_show">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAdmin">确 定</el-button>
      </span>
    </Modal>
  </div>
</template>

<script>
import IPageHeader from '../../../../layouts/system/page-header/index'
import { SystemMenuTreeList } from '../../../../api/system/menu'
import {
  SystemRolePath,
  SystemRolePathDel,
  SystemRolePathInfo,
  SystemRolePathSave,
  SystemRolePathStatusSet,
  SystemRolePathTreeList,
} from '../../../../api/system/rolePath'
import PageCache from '../../../../utils/PageCache'
var pageCache
export default {
  name: 'permissions',
  components: { IPageHeader },
  computed: {},
  data() {
    return {
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,
      formValidate: {
        status: '',
        page: 1,
        limit: 100,
        title: '',
      },
      menu: {
        id: 0,
        title: '',
        role_path: '',
        pid: 0,
        menu_id: 0,
        is_show: 0,
        seq: 0,
      },
      menuAr: [], //栏目分类
      pathAr: [], //权限分栏
      defaultStr: '',
      title: '添加菜单',
      dialogVisible: false,
      total: 0,
      FromData: null,
      classId: 0,
      classList: [],
    }
  },

  created() {
    pageCache = new PageCache(this)
  },
  mounted() {
    this.initView()
  },
  watch: {
    $route(to, from) {
      pageCache.routeView(to, (type, data) => {
        if (type == 'update') {
          Object.assign(this.$data, data)
          this.initView()
        }

        if (type == 'cache') {
          this.$forceUpdate()
          Object.assign(this.$data, data)
        }
      })
    },
  },
  methods: {
    initView: function () {
      this.getList()
    },

    // 添加配置分类
    classAdd() {
      let loading = this.$loading('加载中...')
      var promiseAll = []
      promiseAll.push(SystemMenuTreeList())
      promiseAll.push(SystemRolePathTreeList())
      Promise.all(promiseAll)
        .then((res) => {
          loading.close()
          this.$refs['menu'].resetFields()
          this.menu = this.$utils.resetFields(this.menu, { is_show: 1 })
          this.title = '添加菜单'
          this.menuAr = [{ id: 0, title: '顶级栏目', html: '' }].concat(
            res[0].data
          )
          this.pathAr = [{ id: 0, title: '顶级栏目', html: '' }].concat(
            res[1].data
          )
          this.dialogVisible = true
        })
        .catch((err) => {
          console.log(err)
          loading.close()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    // 编辑
    edit(row, tit, num) {
      console.log(row)
      let loading = this.$loading('加载中...')
      var promiseAll = []
      promiseAll.push(SystemMenuTreeList())
      promiseAll.push(SystemRolePathTreeList())
      promiseAll.push(SystemRolePathInfo({ id: row.id }))
      Promise.all(promiseAll)
        .then((res) => {
          loading.close()
          this.$refs['menu'].resetFields()
          this.menuAr = [{ id: 0, title: '顶级栏目', html: '' }].concat(
            res[0].data
          )
          this.pathAr = [{ id: 0, title: '顶级栏目', html: '' }].concat(
            res[1].data
          )
          if (res[1].code == 200) {
            this.title = '修改栏目'
            this.menu = res[2].data
            this.dialogVisible = true
          } else {
            this.$alert(res.msg, '系统提示')
          }
        })
        .catch((res) => {
          loading.close()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    // 删除
    del(row, tit, num) {
      this.$confirm('此操作将永久删除该栏目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$utils.loading(this, '删除数据中...')
        SystemRolePathDel({ id: row.id })
          .then((res) => {
            this.$utils.loadingClose()
            this.loading = true
            if (res.code == 200) {
              this.getList()
            } else {
              this.$alert(res.msg)
            }
          })
          .catch((err) => {
            this.$utils.loadingClose()
            this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
          })
      })
    },
    // 列表
    getList() {
      this.loading = true
      this.formValidate.status = this.formValidate.status || ''
      SystemRolePath(this.formValidate)
        .then((res) => {
          if (res.code == 200) {
            this.classList = res.data
            this.loading = false
            var defaultAr = this.$refs.xTable.getTreeExpandRecords()
            if (defaultAr.length > 0) {
              var expandAr = []
              setTimeout(() => {
                var expandAr = []
                for (var i in defaultAr) {
                  var b = this.getChinaItem(defaultAr[i].id, this.classList)
                  if (b != null) expandAr.push(b)
                }
                this.$refs.xTable.setTreeExpand(expandAr, true)
              }, 100)
            }
          } else {
            this.loading = false
            this.$alert(res.msg)
          }
        })
        .catch((res) => {
          console.log(res)
          this.loading = false
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    /**
     * 关闭
     */
    editClose: function () {
      this.dialogVisible = false
    },
    /**
     * 修改数据
     */
    subAdmin: function () {
      this.$refs['menu'].validate((valid) => {
        if (valid) {
          let loading = this.$loading('提交数据中...')
          SystemRolePathSave(this.menu)
            .then((res) => {
              loading.close()
              if (res.code == 200) {
                this.dialogVisible = false
                this.$Message.success('操作成功')
                this.getList()
              } else {
                this.$alert(res.msg, '系统提示')
              }
            })
            .catch((err) => {
              loading.close()
              this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
            })
        }
      })
    },

    // 表格搜索
    userSearchs() {
      this.getList()
    },
    /**
     * 当树节点展开或收起时会触发该事件
     */
    tapTreeExpand: function (expanded) {
      //  let data =
    },
    // 修改是否显示
    onchangeIsShow(row) {
      let data = {
        id: row.id,
        is_show: row.is_show,
      }
      SystemRolePathStatusSet(data)
        .then(async (res) => {
          this.$Message.success(res.msg)
          this.getList()
        })
        .catch((res) => {
          this.$Message.error(res.msg)
        })
    },
    /**
     * 获取数据
     */
    getChinaItem: function (id, row) {
      for (var i in row) {
        if (row[i].id == id) {
          return row[i]
        }
      }
      for (var i in row) {
        if (row[i].children != null && row[i].children.length > 0) {
          var b = this.getChinaItem(id, row[i].children)
          if (b != null) {
            return b
          }
        }
      }
      return null
    },
  },
}
</script>
<style scoped></style>
